package com.atguign.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;

/**
 * &#064;program:   gulimall
 * &#064;description:  异常处理
 * &#064;author:  liuxvru
 * &#064;create:  2024-02-04 14:30
 **/
@Slf4j
@ResponseBody
@RestControllerAdvice(basePackages = "com.atguign.gulimall.product.controller")
public class GulimailExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handerVaildException(MethodArgumentNotValidException e){
        log.error(BizCodeEnume.VAILD_EXCEPTION.getMsg(),e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errmp=new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            errmp.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errmp);
    }

    @ExceptionHandler(value = Exception.class)
    public R handerVaildException(Throwable e){
        log.error(e.toString());
        System.out.println(e);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

}
